package com.example.seckilldemo.utils;

import com.example.seckilldemo.pojo.User;
import com.example.seckilldemo.vo.RespBean;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * TODO 生成5000个用户 并插入到数据库中 并进行登录保存userTicket
 *
 * @author 59244
 * @date 2021/11/21 15:28
 */
public class UserUtil {
    private static void createUser(int count) throws Exception {
        //创建用户
        List<User> users = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            User user = new User();
            user.setId(15800000000L+i);
            user.setNickname("user"+i);
            user.setSlat("1a2b3c4d5e");
            user.setPassword(MD5Util.inputPassToDBPass("123456",user.getSlat()));
            user.setLoginCount(1);
            user.setRegisterDate(new Date());
            users.add(user);
        }
        System.out.println("created " + count + " users");
        //插入数据库
//        try (Connection conn = getconn()){
//            try(PreparedStatement ps = conn.prepareStatement(
//                    "INSERT INTO t_user (id,nickname,password,slat,register_date,login_count) " +
//                            "values (?,?,?,?,?,?)")){
//                for (User user : users) {
//                    ps.setLong(1,user.getId());
//                    ps.setString(2,user.getNickname());
//                    ps.setString(3,user.getPassword());
//                    ps.setString(4,user.getSlat());
//                    ps.setTimestamp(5,new Timestamp(user.getRegisterDate().getTime()));
//                    ps.setInt(6,user.getLoginCount());
//                    ps.addBatch();
//                }
//                ps.executeBatch();
//            }
//        }
        System.out.println("inserted to DB");
        //登录，获取userTicket,保存在config.txt中，便于jmeter压测
        String urlString = "http://localhost:8080/login/dologin";
        File file = new File("E:\\Jmeter\\config.txt");
        if(file.exists()){
            file.delete();
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");
        randomAccessFile.seek(0);
        for (User user:users) {
            URL url = new URL(urlString);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            String params = "mobile=" + user.getId() + "&password=" + MD5Util.inputPassToFormPass("123456");
            outputStream.write(params.getBytes());
            outputStream.flush();
            InputStream inputStream = httpURLConnection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            while((len = inputStream.read(buff))>=0){
                byteArrayOutputStream.write(buff, 0, len);
            }
            inputStream.close();
            byteArrayOutputStream.close();
            String response = new String(byteArrayOutputStream.toByteArray());
            ObjectMapper objectMapper = new ObjectMapper();
            System.out.println(response);
            RespBean respBean = objectMapper.readValue(response, RespBean.class);
            System.out.println(respBean);
            String userTicket = (String) respBean.getObj();
            System.out.println("created userTicket:"+user.getId());
            String row = user.getId() + "," + userTicket;
            randomAccessFile.seek(randomAccessFile.length());
            randomAccessFile.write(row.getBytes());
            randomAccessFile.write("\r\n".getBytes());
            System.out.println("writed into file:" + user.getId());
        }
        randomAccessFile.close();
        System.out.println("done");
    }

    private static Connection getconn() throws Exception {
        String JDBC_URL = "jdbc:mysql://localhost:3306/seckill?useUnicode=true&charactorEncoding=UTF-8&" +
                "serverTimezone=Asia/Shanghai";
        String JDBC_USER = "root";
        String JDBC_PASSWORD = "sean";
        String driver = "com.mysql.cj.jdbc.Driver";
        Class.forName(driver);
        return DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
    }

    public static void main(String[] args) throws Exception {
        createUser(5000);
    }
}
